const request = require("../../utils/request");
const config = require("../../config");
const eventBus = require("../../utils/eventBus");
const recommendation = require("../../utils/recommendation");
const app = getApp();

// 获取baseURL
const baseURL = config.development.baseURL;

Page({
  data: {
    courseId: null,
    courseInfo: null,
    schedules: [],
    comments: [],
    loading: true,
    activeTab: "detail",
    tabs: [
      { key: "detail", name: "详情" },
      { key: "catalog", name: "目录" },
      { key: "comment", name: "评价" },
    ],
    isLoggedIn: false,
    similarCourses: [], // 相似课程
    loadingSimilar: false, // 加载相似课程的状态
    recoSimilarCourses: [], // 算法推荐的相似课程
    hasRecommendation: false, // 是否有算法推荐
    isFavorite: false, // 是否已收藏
  },

  onLoad(options) {
    const { id } = options;
    this.setData({
      courseId: id,
      activeTab: "detail",
    });
    
    // 检查登录状态
    this.checkLoginStatus();
    
    // 记录页面浏览事件
    if (id) {
      app.analytics.pageView('course_detail', { course_id: id });
    }
    
    this.fetchCourseDetail();
    eventBus.on('commentUpdated', this.handleCommentUpdate.bind(this));
  },
  
  // 页面显示时检查登录状态
  onShow() {
    this.checkLoginStatus();
  },
  
  // 检查登录状态
  checkLoginStatus() {
    const isLoggedIn = app.globalData.isLoggedIn;
    
    this.setData({ isLoggedIn });
    
    // 如果未登录，提示用户并返回首页
    if (!isLoggedIn) {
      wx.showModal({
        title: '提示',
        content: '请先登录后查看课程详情',
        showCancel: false,
        success: () => {
          wx.switchTab({
            url: '/pages/index/index'
          });
        }
      });
    }
  },

  onUnload() {
    eventBus.off('commentUpdated', this.handleCommentUpdate)
  },

  handleCommentUpdate(data) {
    if (data.courseId === this.data.courseId) {
      this.fetchCourseDetail()
    }
  },

  onBack() {
    wx.navigateBack({
      delta: 1,
      fail: () => {
        wx.switchTab({
          url: "/pages/index/index",
        });
      },
    });
  },

  async fetchCourseDetail() {
    try {
      const { data } = await request({
        url: `/api/course/${this.data.courseId}`,
      });

      // 计算平均评分
      const averageRating =
        data.comments.length > 0
          ? (
              data.comments.reduce((sum, comment) => sum + comment.rating, 0) /
              data.comments.length
            ).toFixed(1)
          : "0.0";

      this.setData({
        courseInfo: {
          id: data.id,
          title: data.title,
          price: data.price,
          image_url: data.image_url ? `${baseURL}${data.image_url}` : "",
          description: data.description,
          total_chapters: data.total_chapters, // 使用总章节数
          enroll_count: data.enroll_count,
          rating: data.rating,
          start_time: data.start_time,
          category_name: data.category_name,
          level: data.level,
          teacher: {
            name: data.teacher_name,
            avatar: data.teacher_avatar
              ? `${baseURL}${data.teacher_avatar}`
              : "",
            title: data.teacher_title,
            description: data.teacher_description,
            course_count: data.teacher_course_count,
            student_count: data.teacher_student_count,
          },
        },
        schedules: data.schedules.map((schedule) => ({
          id: schedule.id,
          title: schedule.title,
          content: schedule.content,
          sort: schedule.sort,
          duration: schedule.duration || 45, // 课时时长（分钟）
          video_url: schedule.video_url, // 视频链接
        })),
        comments: data.comments.map((comment) => ({
          id: comment.id,
          content: comment.content,
          rating: comment.rating,
          user: {
            nickname: comment.nickname,
            avatar: comment.avatar ? `${baseURL}${comment.avatar}` : "",
          },
          created_at: this.formatDate(comment.created_at),
        })),
        // 修正评价相关数据
        averageRating,
        floorRating: Math.floor(averageRating),
        hasHalfStar: averageRating % 1 >= 0.5,
        // 修正评论数据结构
        reviews: data.comments.map((comment) => ({
          id: comment.id,
          content: comment.content,
          rating: comment.rating,
          ratingDisplay: `${comment.rating}.0`,
          avatar: comment.avatar ? `${baseURL}${comment.avatar}` : "",
          userName: comment.nickname,
          date: this.formatDate(comment.created_at),
        })),
        averageRating,
        floorRating: Math.floor(averageRating),
        hasHalfStar: averageRating % 1 >= 0.5,
        // 移除数据库相似课程，只使用算法推荐的相似课程
        similarCourses: [],
        loading: false,
      });
      
      // 获取推荐系统的相似课程
      this.fetchRecommendedSimilarCourses();
    } catch (error) {
      console.error("获取课程详情失败:", error);
      wx.showToast({
        title: "获取课程详情失败",
        icon: "none",
      });
    }
  },

  // 从推荐系统获取相似课程
  async fetchRecommendedSimilarCourses() {
    this.setData({ loadingSimilar: true });
    
    try {
      // 先检查推荐系统状态
      const status = await recommendation.getRecommendationStatus().catch(() => null);
      console.log('推荐系统状态:', status);
      
      if (!status || (!status.cf_model?.loaded && !status.content_model?.loaded)) {
        console.log('推荐系统未就绪，使用常规相似课程');
        this.setData({ 
          loadingSimilar: false,
          hasRecommendation: false 
        });
        return;
      }
      
      // 获取推荐的相似课程
      const similarCourseData = await recommendation.getSimilarCourses(this.data.courseId, 5);
      console.log('获取到的相似课程数据:', similarCourseData);
      
      // 确保我们获取了正确的数据结构
      if (similarCourseData && similarCourseData.similar_courses && similarCourseData.similar_courses.length > 0) {
        // 获取所有相似课程的ID
        const courseIds = similarCourseData.similar_courses.map(item => item.course_id);
        console.log('准备获取的课程IDs:', courseIds);
        
        // 单独获取每个课程的详细信息，避免批量接口的404问题
        const coursesPromises = courseIds.map(async (courseId) => {
          try {
            const result = await request({
              url: `/api/course/${courseId}`
            });
            if (result.code === 200 && result.data) {
              return result.data;
            }
            return null;
          } catch (err) {
            console.error(`获取课程 ${courseId} 详情失败:`, err);
            return null;
          }
        });
        
        // 等待所有课程信息获取完成
        const coursesResults = await Promise.all(coursesPromises);
        
        // 过滤掉获取失败的课程
        const validCourses = coursesResults.filter(course => course !== null);
        console.log('成功获取的课程数量:', validCourses.length);
        
        if (validCourses.length > 0) {
          // 处理课程数据
          const processedCourses = validCourses.map(course => {
            const similarityInfo = similarCourseData.similar_courses.find(c => c.course_id === course.id);
            const similarity = similarityInfo ? similarityInfo.similarity : 0;
            // 在JS中预先计算百分比，避免在WXML中使用toFixed
            const similarityPercent = Math.round(similarity * 100);
            
            return {
              id: course.id,
              title: course.title,
              price: course.price,
              imageUrl: course.image_url ? `${baseURL}${course.image_url}` : "",
              enrollCount: course.enroll_count || 0,
              tags: typeof course.tags === 'string' ? course.tags.split(',') : (Array.isArray(course.tags) ? course.tags : []),
              similarity: similarity,
              similarityPercent: similarityPercent // 添加格式化后的相似度百分比，但在WXML中不显示
            };
          });
          
          // 按相似度排序
          processedCourses.sort((a, b) => b.similarity - a.similarity);
          console.log('处理后的推荐课程:', processedCourses);
          
          this.setData({
            recoSimilarCourses: processedCourses,
            hasRecommendation: processedCourses.length > 0,
            loadingSimilar: false
          });
        } else {
          console.log('没有获取到有效的课程详情');
          this.setData({ 
            loadingSimilar: false,
            hasRecommendation: false 
          });
        }
      } else {
        console.log('没有获取到有效的相似课程数据');
        this.setData({ 
          loadingSimilar: false,
          hasRecommendation: false 
        });
      }
    } catch (error) {
      console.error('获取推荐相似课程失败:', error);
      this.setData({ 
        loadingSimilar: false,
        hasRecommendation: false 
      });
    }
  },

  // 格式化日期
  formatDate(dateStr) {
    const date = new Date(dateStr);
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(
      2,
      "0"
    )}-${String(date.getDate()).padStart(2, "0")}`;
  },

  switchTab(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({ activeTab: tab });
  },

  // 添加相似课程点击处理方法
  onCourseTap(e) {
    const courseId = e.currentTarget.dataset.id;
    wx.redirectTo({
      url: `/packageA/course-detail/index?id=${courseId}`,
    });
    
    // 记录推荐课程点击事件
    app.analytics.clickEvent('recommended_course', 'course_detail');
  },
  
  // 预约按钮点击处理方法
  onBookingTap() {
    if (!this.data.courseInfo) return;
    
    // 检查登录状态
    if (!this.data.isLoggedIn) {
      wx.showModal({
        title: '提示',
        content: '请先登录后进行预约',
        showCancel: false,
        success: () => {
          wx.switchTab({
            url: '/pages/index/index'
          });
        }
      });
      return;
    }
    
    const { id, title, price, image_url } = this.data.courseInfo;
    wx.navigateTo({
      url: `/packageA/course-booking/index?id=${id}&title=${encodeURIComponent(title)}&price=${price}&imageUrl=${encodeURIComponent(image_url)}`,
      fail: (err) => {
        console.error("跳转预约页面失败:", err);
        wx.showToast({
          title: "跳转预约页面失败",
          icon: "none"
        });
      }
    });
  },

  // 收藏课程
  toggleFavorite() {
    // ... existing code ...
    
    // 记录收藏/取消收藏事件
    app.analytics.favoriteCourse(this.data.courseInfo.id, !this.data.isFavorite);
    
    // ... 继续收藏逻辑 ...
  },
  
  // 购买课程
  onBuyNow() {
    // ... existing code ...
    
    // 记录购买事件（开始购买流程）
    app.analytics.clickEvent('buy_now', 'course_detail');
    
    // ... 继续购买逻辑 ...
  },
  
  // 课程评分
  submitRating(e) {
    const rating = e.detail.value;
    // ... existing code ...
    
    // 记录评分事件
    app.analytics.rateCourse(this.data.courseInfo.id, rating, '');
    
    // ... 继续评分逻辑 ...
  },
});
